package czy.demo.config.jpa;

import czy.demo.entity.User;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Optional;

/* JPA审计功能，获取审计员 */
@Component("auditorAware")
public class DefaultAuditorAware implements AuditorAware {

    /* 获取审计员，填充到CreateBy等字段中 */
    @Override
    public Optional<User> getCurrentAuditor() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context != null) {
            Authentication authentication = context.getAuthentication();
            if (authentication != null) {
                User user = (User) authentication.getPrincipal();
                if (user != null) {
                    return Optional.of(user);
                }
            }
        }
        return Optional.ofNullable(InitService.getRoot());
    }

}
